<?php
namespace app\admin\controller;
use think\Db;
use think\Controller;
use think\facade\Request;
use think\Validate;
use app\admin\model\Teacher as TeacherModel;
use app\admin\controller\Section;
class Rule extends Common
{
    /**规则列表
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function lists(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('sign_rule')
                ->where('is_del',0)
                ->where('rule_name', 'like', "%" . $keyword . "%")
                ->order('sort asc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            if (! empty($list)) {

                foreach ($list['data'] as $k => $v) {

                    if($v['person_type']=="0"){
                        $list['data'][$k]['person_type'] = '全部';
                    }else{
                        $arr = unserialize( $v['person_type']);
                        $str = '';
                        foreach ($arr as $val){

                            $str .= Db::name('teacher')->where('id',$val)->value('true_name');
                            $str .= ",";
                        }
                        $list['data'][$k]['person_type'] = $str;
                    }


                    if($v['work_time']==NULL){

                    }else{
                        $arr = unserialize( $v['work_time']);
                        $week_day = ['周日','周一','周二','周三','周四','周五','周六'];
                        $str = "";
                        foreach ($arr as $key=>$val){
                            $str.=$week_day[$val]."， ";
                        }
                        $list['data'][$k]['work_time']=$str;
                    }

                    $list['data'][$k]['create_time'] = toDate($v['create_time']);

                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('rule_list');
    }

    /**添加规则
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ruleAdd(){
        if(Request::isAjax()){
            $data = input('post.');

            if($data['work_time']){
                $data['work_time'] = serialize($data['work_time']);
            }
            if($data['sub_workday']){
                $data['sub_workday'] = serialize($data['sub_workday']);
            }
            if($data['add_workday']){
                $data['add_workday'] = serialize($data['add_workday']);
            }
            if($data['person_type']!=''){
                $data['person_type'] = serialize($data['person_type']);
            }else{
                $data['person_type'] = 0;
            }
            if(substr($data['late_max_time'],0,2)>=12){
                $data['use_time_type']  = 2;
            }
            $data['creater']        = session('username');
            $data['create_time']    = time();
            Db::name('sign_rule')->insert($data);
            $log = [
                'content'=>'添加规则'.$data['rule_name']
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('成功',url('lists'));

        }else{
            $sectionGroup = Db::name('section')->where('is_del',0)->select();
            $this->assign('sectionGroup',$sectionGroup);
            $this->assign('title',lang('add').lang('rule'));
            $this->assign('info','null');
            return view('ruleForm');
        }
    }

    /**编辑规则
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ruleEdit(){
        if(Request::isAjax()){

            $info = Db::name('sign_rule')->where('id',input('id'))->find();

            if($info['add_workday']!=''){
                $add_workday = unserialize( $info['add_workday'] );
                foreach ($add_workday as $k=>$v){
                    $add_workday[$k] = explode('/',$v);
                }

                $info['add_workday'] = $add_workday;
            }


            if($info['sub_workday']!='') {
                $sub_workday = unserialize( $info['sub_workday'] );
                foreach ($sub_workday as $k => $v) {
                    $sub_workday[$k] = explode('/', $v);
                }

                $info['sub_workday'] = $sub_workday;

            }
            if($info['work_time']!='') {

                $info['work_time'] = unserialize( $info['work_time'] );

            }
            if($info['person_type']=="0"){

            }else{
                $arr = unserialize( $info['person_type'] );
                foreach ($arr as $k=>$val){
                    $true_name = Db::name('teacher')->where('id',$val)->value('true_name');
                    $d[$k]['true_name']= $true_name;
                    $d[$k]['id']= $val;
                }

                $info['person_type'] = $d;


            }
            return json([
                'data'=>$info,
                'sub_workday'=>$info['sub_workday'],
                'add_workday'=>$info['add_workday'],
                'person'=>$info['person_type'],
                'work_time'=>$info['work_time']
            ]);

        }else{

            $info = Db::name('sign_rule')->where('id',input('id'))->find();

            if($info['add_workday']!=''){
                $add_workday = unserialize( $info['add_workday'] );
                foreach ($add_workday as $k=>$v){
                    $add_workday[$k] = explode('/',$v);
                }
                $this->assign('add_workday', $info['add_workday']);

                $info['add_workday'] = $add_workday;
            }


            if($info['sub_workday']!='') {
                $sub_workday = unserialize( $info['sub_workday'] );
                foreach ($sub_workday as $k => $v) {
                    $sub_workday[$k] = explode('/', $v);
                }
                $this->assign('sub_workday', $info['sub_workday']);

                $info['sub_workday'] = $sub_workday;

            }
            if($info['person_type']==0){

            }else{
                $arr = unserialize( $info['person_type'] );
                foreach ($arr as $k=>$val){
                    $true_name = Db::name('teacher')->where('id',$val)->value('true_name');
                    $d[$k]['true_name']= $true_name;
                    $d[$k]['id']= $val;
                }
                $this->assign('person', $info['person_type']);
                $info['person_type'] = $d;


            }
            if($info['work_time']!='') {

                $info['work_time'] =  unserialize( $info['work_time'] );

            }
            $this->assign('info', $info);
            $this->assign('title',lang('edit').lang('rule'));
            $this->assign('id',input('id'));
            return view('ruleEdit');
        }
    }

    /**保存编辑
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function saveEdit(){

        if(Request::isAjax()){
            $data = input('post.');
            if($data['work_time']){
                $data['work_time'] = serialize($data['work_time']);
            }
            if($data['sub_workday']){
                $data['sub_workday'] = serialize($data['sub_workday']);
            }
            if($data['add_workday']){
                $data['add_workday'] = serialize($data['add_workday']);
            }
            if($data['person_type']!=''){
                $data['person_type'] = serialize($data['person_type']);
            }else{
                $data['person_type'] = 0;
            }
            if(substr($data['late_max_time'],0,2)>=12){
                $data['use_time_type']  = 2;
            }
            Db::name('sign_rule')->update($data);
            $rulename =  Db::name('sign_rule')->where('id', $data['id'])->value('rule_name');
            $log = [
                'content'=>'删除规则'.$rulename
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('成功',url('lists'));

        }
    }

    /**删除规则
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function ruleDel(){
        $rule_id=input('post.rule_id');
        if (session('aid')==1){
            Db::name('sign_rule')->where('id', $rule_id)->update(['is_del' => 1]);
            $rulename =  Db::name('sign_rule')->where('id', $rule_id)->value('rule_name');
            $log = [
                'content'=>'删除规则'.$rulename
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('删除成功!');
        }else{
            $this->error('您没有删除规则的权限!');
        }
    }

    /**修改规则状态
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function ruleState(){
        $rule_id=input('post.id');
        $status=input('post.status');

        if (empty($rule_id)){
            $this->error('规则ID不存在');
        }

        Db::name('sign_rule')->where('id', $rule_id)->update(['status'=>$status]);
        $rulename =  Db::name('sign_rule')->where('id', $rule_id)->value('rule_name');
        $log = [
            'content'=>'修改规则状态'.$rulename
        ];
        $wed = new Weblog();
        $wed->insert($log);
        $this->success('规则状态修改成功');
    }

    /**修改排序
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function ruleSort(){
        $data = input('post.');
        if(Db::name('sign_rule')->update($data)!==false){
            return $result = ['code'=>1,'msg'=>'排序更新成功!','url'=>url('lists')];
        }else{
            return $result = ['code'=>0,'msg'=>'排序更新失败!'];
        }
    }

    /**教师列表
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function teacher(){

        if (request()->isAjax()) {

            input('post.id')?$section_id = input('id'):$section_id="";
            if($section_id!=''){
                $section = new Section();
                $str = $section_id;
                foreach ($section->showCate($section_id) as $k=>$v){
                    $str .= ",".$v['section_id'];
                }
                $list = Db::name('teacher t')
                    ->join('section s','t.section_id=s.section_id','left')
                    ->field('t.teacher_no,t.true_name,t.sex,t.id,s.title')
                    ->where('t.is_del',0)
                    ->where('s.is_del',0)
                    ->where('t.section_id','in',$str)
                    ->order('t.section_id desc')
                    ->select();
            }else{
                $list = Db::name('teacher t')
                    ->join('section s','t.section_id=s.section_id','left')
                    ->field('t.teacher_no,t.true_name,t.sex,t.id,s.title')
                    ->where('t.is_del',0)
                    ->where('s.is_del',0)
                    ->order('t.section_id desc')
                    ->select();
            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list];
        }

        $section = new Section();
        $this->assign('section',$section->showCate());
        return $this->fetch('teacher');
    }

    /**检查教师是否存在重复规则
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkTeacher(){
        if (request()->isAjax()) {

           $data = input('post.all_data');

            $rule_datas = Db::name('sign_rule')->where('is_del',0)->select();
            $d = [];
            foreach ($rule_datas as $k=>$v){
                $person_arr = unserialize($v['person_type']);
                $str = '';
                foreach ($data as $key=>$val){
                    if(in_array($val['id'],$person_arr)){
                        $teacher_name = Db::name('teacher')->where('id',$val['id'])->value('true_name');
                        $str.=$teacher_name."已存在于规则".$v['rule_name'].',';
                        if(count($d)==0){
                            $d[0] = '';
                        }
                        $d[] = $val['id'];
                    }
                }
            }

          return json([
              'msg'=>$str,
              'data'=>$d
          ]);

        }

    }

    /**添加节假日
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function holidayEnd(){

        if(Request::isAjax()){
            $year = date("Y",time());
            $holiday = Db::name('holiday')->where('year',$year)->where('status',1)->where('is_del',0)->select();

            return $holiday;
        }
    }

    /**
     * 假期管理
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function holiday(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('holiday')
                ->where('is_del',0)
                ->where('name|year', 'like', "%" . $keyword . "%")
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            if (! empty($list)) {

                foreach ($list['data'] as $k => $v) {

                    $list['data'][$k]['create_time'] = toDate($v['create_time']);

                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('holiday_list');

    }

    /**假期添加
     * @return mixed
     */
    public function holidayAdd(){
        if(Request::isAjax()){
            $data = input('post.');
            $data['create_time'] = time();
            $data['creater']     = session('username');

            Db::name('holiday')->insert($data);
            $log = [
                'content'=>'添加假期'.$data['name']
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('成功',url('holiday'));

        }else{
            $this->assign('title',lang('add').'假期');
            $this->assign('info','null');
            return $this->fetch('holiday_add');
        }
    }

    /**
     * 假期编辑
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function holidayEdit(){
        if(Request::isAjax()){
            $data = input('post.');

            Db::name('holiday')->update($data);
            $log = [
                'content'=>'编辑假期'.$data['name']
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('成功',url('holiday'));

        }else{
            $this->assign('title',lang('edit').'假期');
            $info = Db::name('holiday')->where('id',input('id'))->find();
            $this->assign('info',json_encode($info,true));
            return $this->fetch('holiday_add');
        }
    }

    /**删除假期
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function holidayDel(){
        $holiday_id=input('post.holiday_id');
        if (session('aid')==1){
            Db::name('holiday')->where('id', $holiday_id)->update(['is_del' => 1]);
            $rulename =  Db::name('holiday')->where('id', $holiday_id)->value('name');
            $log = [
                'content'=>'删除假期'.$rulename
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('删除成功!');
        }else{
            $this->error('您没有删除假期的权限!');
        }
    }

    /**修改假期状态
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function  holidayState(){
        $holiday_id=input('post.id');
        $status=input('post.status');

        if (empty($holiday_id)){
            $this->error('假期ID不存在');
        }

        Db::name('holiday')->where('id', $holiday_id)->update(['status'=>$status]);
        $rulename =  Db::name('holiday')->where('id', $holiday_id)->value('name');
        $log = [
            'content'=>'修改假期状态'.$rulename
        ];
        $wed = new Weblog();
        $wed->insert($log);
        $this->success('假期状态修改成功');
    }
}